/**
 * @version: V1.0
 * @Title: Test02_LevelMaxWidth.java
 * @Description:
 * @author wangshipeng
 * @date 2022-01-24 22:31
 * @Copyright: 2022-01-24
 */

package com.peng.tree.test_code;

import com.peng.tree.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author wangshipeng
 * @ClassName: Test02_LevelMaxWidth
 * @Description: 求树上最宽的层的宽度是多少
 * @date 2022-01-24 22:31
 */
public class Test02_LevelMaxWidth {

    public static int getMaxWidth(Node head) {

        int maxWidth = 0;

        if (head == null) {
            return maxWidth;
        }
        Node curLastNode = head;
        Node nextLastNode = null;
        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        int width = 0;
        while (!queue.isEmpty()) {
            Node cur = queue.poll();
            width++;

            if (cur.left != null) {
                queue.add(cur.left);
                nextLastNode = cur.left;
            }
            if (cur.right != null) {
                queue.add(cur.right);
                nextLastNode = cur.right;
            }


            //结算
            if (cur == curLastNode) {
                maxWidth = Math.max(maxWidth, width);
                width = 0;
                curLastNode = nextLastNode;
                nextLastNode = null;
            }

        }

        return maxWidth;
    }

    public static void main(String[] args) {
        Node node = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        Node node7 = new Node(7);
        Node node8 = new Node(8);
        Node node9 = new Node(9);

        node.left = node2;
        node.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node4.left = node8;
        node4.right = node9;
        /*
                   1
             2              3
           4    5         6     7
         8   9

         */

        int maxWidth = getMaxWidth(node);
        System.out.println(maxWidth);


    }
}
